﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Configuration;
using System.Web;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.ComponentModel;
using eBlog.Cache;

namespace eBlog.Common
{
    public class MailSender
    {
        public static void Send(string server, string sender, string recipient, string subject, string body, bool isBodyHtml, Encoding encoding, bool isAuthentication, params string[] files)
        {
            SmtpClient smtpClient = new SmtpClient(server);
            MailMessage message = new MailMessage(sender, recipient);
            message.IsBodyHtml = isBodyHtml;

            message.SubjectEncoding = encoding;
            message.BodyEncoding = encoding;

            message.Subject = subject;
            message.Body = body;


            message.Attachments.Clear();
            if (files != null && files.Length != 0)
            {
                for (int i = 0; i < files.Length; ++i)
                {
                    Attachment attach = new Attachment(files[i]);
                    message.Attachments.Add(attach);
                }
            }

            if (isAuthentication == true)
            {
                smtpClient.Credentials = new NetworkCredential(SmtpConfig.Create().SmtpSetting.ServerUserName,
                    SmtpConfig.Create().SmtpSetting.ServerUserPassword);
            }
            
           // smtpClient.Send(message);

            smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
            //object mailSendState = message;
            //smtpClient.SendAsync(message, mailSendState);
            smtpClient.SendAsync(message, "ok");


        }

        public static void smtpClient_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            string state = (string)e.UserState;

            if (e.Cancelled)
            {
            }
            if (e.Error != null)
            {
            }

        }

        public static void Send(string recipient, string subject, string body)
        {
            Send(SmtpConfig.Create().SmtpSetting.ServerAddress, SmtpConfig.Create().SmtpSetting.Sender, recipient, subject, body, true, Encoding.UTF8, true, null);
        }

        public static void Send(string Recipient, string Sender, string Subject, string Body)
        {
            Send(SmtpConfig.Create().SmtpSetting.ServerAddress, Sender, Recipient, Subject, Body, true, Encoding.UTF8, true, null);
        }
        
    }

    public class SmtpSetting
    {
        private string _server;

        public string ServerAddress
        {
            get { return _server; }
            set { _server = value; }
        }
        private bool _authentication;

        public bool Authentication
        {
            get { return _authentication; }
            set { _authentication = value; }
        }
        private string _user;

        public string ServerUserName
        {
            get { return _user; }
            set { _user = value; }
        }
        private string _sender;

        public string Sender
        {
            get { return _sender; }
            set { _sender = value; }
        }
        private string _password;

        public string ServerUserPassword
        {
            get { return _password; }
            set { _password = value; }
        }
        private int _port;

        public int ServerPort
        {
            get { return _port; }
            set { _port = value; }
        }

    }

    public class SmtpConfig
    {
        private static SmtpConfig _smtpConfig;
        private string ConfigFile
        {
            get
            {
                string configPath = ConfigurationManager.AppSettings["SmtpConfigPath"];
                if (string.IsNullOrEmpty(configPath) || configPath.Trim().Length == 0)
                {
                    configPath = HttpContext.Current.Request.MapPath("/Config/email.config");
                }
                else
                {
                    if (!Path.IsPathRooted(configPath))
                        configPath = HttpContext.Current.Request.MapPath(Path.Combine(configPath, "SmtpSetting.config"));
                    else
                        configPath = Path.Combine(configPath, "SmtpSetting.config");
                }
                return configPath;
            }
        }
        public SmtpSetting SmtpSetting
        {
            get
            {
                if (DataCache.Exists("System_Email_SMTP_CONFIG"))
                {
                    return (SmtpSetting)DataCache.GetCache("System_Email_SMTP_CONFIG");
                }
                else
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(this.ConfigFile);
                    SmtpSetting smtpSetting = new SmtpSetting();
                    smtpSetting.ServerAddress = doc.DocumentElement.SelectSingleNode("/Email/ServerAddress").InnerText;
                    smtpSetting.Authentication = Convert.ToBoolean(doc.DocumentElement.SelectSingleNode("/Email/Authentication").InnerText);
                    smtpSetting.ServerUserName = doc.DocumentElement.SelectSingleNode("/Email/ServerUserName").InnerText;
                    smtpSetting.ServerUserPassword = doc.DocumentElement.SelectSingleNode("/Email/ServerUserPass").InnerText;
                    smtpSetting.Sender = doc.DocumentElement.SelectSingleNode("/Email/Sender").InnerText;
                    smtpSetting.ServerPort = int.Parse(doc.DocumentElement.SelectSingleNode("/Email/ServerPort").InnerText);

                    DataCache.SetCache("System_Email_SMTP_CONFIG", smtpSetting);

                    return smtpSetting;
                }
            }
        }
        private SmtpConfig()
        {

        }
        public static SmtpConfig Create()
        {
            if (_smtpConfig == null)
            {
                _smtpConfig = new SmtpConfig();
            }
            return _smtpConfig;
        }
    }
}
